# 执行main方法
import argparse
from DataService import DataService
import logging
import os
import signal
import sys
import threading  
from utils.db_pool import MySQLConnectionPool
import queue

pool = MySQLConnectionPool()

# utf-8编码
logging.basicConfig(filename='error/info.log', level=logging.INFO, encoding='utf-8')
def signal_handler(signal, frame):
    # 记录日志
    logging.info('接收到信号: %s', signal)
    # 释放example.log文件句柄
    logging.shutdown()
    sys.stdout.flush()
    sys.stderr.flush()
    os._exit(0)
    
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGSEGV, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)

dataService = DataService()
dataService.get_apply_key()

def sync_api_data(thread_id, table_name, modelId, result_queue):
    try:
        conn = pool.get_connect()
        cursor = conn.cursor()
        limit = 5
        skip_rows = thread_id * limit
        # 从table_name表中获取一批数据
        sql_query = f"SELECT id,phone,month FROM {table_name} WHERE is_check=0 LIMIT {limit} OFFSET {skip_rows}"
        cursor.execute(sql_query)
        # print(f"Executing SQL query: {sql_query}")
        results = cursor.fetchall()
        
        if not results:
            result_queue.put(False)
            return
        

        servCode = "EXTLAB-AA25"
        # 处理这批数据
        for row in results:
            id, phone, mon = row
            # 转成字符串
            mon = str(mon)
            requestXml = dataService.create_xml_phone(servCode, modelId, phone, mon)
            # print(requestXml)
            responseXml = dataService.do_post(requestXml)
            # print(responseXml)
            # 解析responseXml
            # 如果ResponseCode=0，解析ServResult，保存结果
            responseRs = dataService.parse_xml(responseXml)
            rsCode, billing, value, is_valid = responseRs
            
            # 错误日志目录
            errorLogDir = "/data/dev10086/result/"
            
            # rsCode=0表示成功
            if rsCode != "0":
                # 写入错误日志，type
                with open(f"{errorLogDir}{type}_error.log", "a") as f:
                    f.write(f"{id}|{phone}|{mon}|{rsCode}\n")
                    
                sql = f"UPDATE {table_name} SET is_check=1 WHERE id={id}"
                cursor.execute(sql)
                conn.commit()
                continue
            else:
                # 保存结果到数据库
                sql = f"UPDATE {table_name} SET is_billing={billing}, value={value}, is_valid={is_valid}, is_check=1 WHERE id={id}"
                cursor.execute(sql)
                conn.commit()
        
        result_queue.put(True)
        
    except Exception as e:
        logging.exception('Thread %s encountered an error: %s', thread_id, e)
        result_queue.put(False)
        
    finally:
        cursor.close()
        conn.close()

def main():
    parser = argparse.ArgumentParser()
    # parser.add_argument("--phone", help="Phone number")
    parser.add_argument("--type", help="the model type's sign, such as 'zaixin_model_hq' or 'zaixin_model_zx' or 'zaixin_model_zf'")
    args = parser.parse_args()

    # 服务编码
    type = args.type
    if type is None:
        print("please input the type")
        return

    # 服务编码 modelId=[zx|hq|zf] 
    # 装修 ：zaixin_model_zx zx 1026556 zaixin_zhuangxiu_rsltout_20240201.txt
    # 婚庆：zaixin_model_hq hq 87416 zaixin_hunqing_rsltout_20240201.txt
    # 支付：zaixin_model_zf zf 51908 zaixin_zhifu_rsltout_20240201.txt
    # 教育：zaixin_model_jy jy
    # 法律：zaixin_model_fl fl
    if type == "zx":
        modelId = "zaixin_model_zx"
        table_name = "data_zhuangxiu"
        # month = "20240101"
        
    elif type == "hq":
        modelId = "zaixin_model_hq"
        table_name = "data_hunqing"
        # month = "20240111"
        
    elif type == "zf":
        modelId = "zaixin_model_zf"
        table_name = "data_zhifu"
        # month = "20240121"
        
    elif type == "jy":
        modelId = "zaixin_model_jy"
        table_name = "data_jiaoyu"
        
    elif type == "fl":
        modelId = "zaixin_model_fl"
        table_name = "data_falv"
        
    else:
        print("please input the correct type")
        return

    
    # 从table_name表中分批次获取所有数据
    # 定义每批次读取的数据量

    while True:
        threads = []
        result_queue = queue.Queue()
        
        for i in range(10):  
            t = threading.Thread(target=sync_api_data, args=(i, table_name, modelId, result_queue))  
            threads.append(t)
            
            t.start()  
        
        # 等待所有线程完成  
        for t in threads:  
            t.join()
            
        # 获取所有线程的返回值  
        results = []  
        while not result_queue.empty():  
            results.append(result_queue.get())  
  
        # print(results)
        # 检查所有结果是否都是False  
        if all(result == False for result in results):  
            print("所有线程的结果都是False，结束进程。")  
            break  # 如果所有线程都返回False，则退出循环  
        # else:  
            # print("有线程的结果不是False，继续下一轮同步。")  
        
        
    
if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        logging.exception('程序异常退出: %s', e)
        raise